import requests
from bs4 import BeautifulSoup
import pandas as pd

def get_maoyan_movies(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        movies = []
        for item in soup.find_all('div', class_='board-item-main'):
            name = item.find('p', class_='name').text.strip()
            release_time = item.find('p', class_='releasetime').text.strip()
            star = item.find('p', class_='star').text.strip()
            score = item.find('p', class_='score').text.strip()
            movies.append([name, release_time, star, score])
        return movies
    else:
        print("Failed to retrieve data from Maoyan.")
        return []

def save_to_excel(movies, filename):
    df = pd.DataFrame(movies, columns=['电影名称', '上映时间', '主演', '评分'])
    df.to_excel(filename, index=False)
    print(f"Data has been saved to {filename} successfully.")

if __name__ == "__main__":
    url = 'https://maoyan.com/board/4'
    movies = get_maoyan_movies(url)
    if movies:
        print(movies)
        save_to_excel(movies, 'maoyan_movies.xlsx')